<template>
  <div class="common-container">
    <div class="header">
      <div class="header_left">
        <!-- <el-select v-model="parkId" placeholder="请选择园区"  clearable @clear="clearNickname"  style="width: 300px;margin-left: 15px;">
            <el-option v-for="item in ParkList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select> -->

        <el-input
          v-model="search_val"
          placeholder="请输入建筑物名称"
          clearable
          @clear="clearNickname"
          size="small"
          style="width: 220px"
        >
          <el-button
            slot="append"
            :icon="loadingSearch ? 'el-icon-loading' : 'el-icon-search'"
            @click="searchClick"
          >
          </el-button>
        </el-input>

        <el-select
          size="small"
          style="width: 190px; margin-left: 15px"
          clearable
          @change="changeOrgId"
          @visible-change="enterpriseChange"
          @keyup.enter.native="searchList"
          v-loadMore="loadMore"
          v-model="selectedValue"
          placeholder="请选择单位"
          filterable
          remote
          :remote-method="remoteMethod"
          @clear="handleClear"
          v-if="user.roleName == 'TENANT_ADMIN' || user.roleName == 'ORG_ADMIN'"
        >
          <el-option
            v-for="item in projectList"
            :label="item.orgName"
            :value="item.id"
            :key="item.id"
          >
          </el-option>
          <div
            class="div_box"
            v-loading="loading"
            :style="loading ? '' : 'display: none;'"
          ></div>
        </el-select>
        <!-- <el-button size="small" style="margin-left: 15px;" @click="searchClick">查询</el-button> -->
      </div>
      <div class="header_right">
        <el-button
          size="small"
          style="margin-left: 15px"
          icon="el-icon-plus"
          @click="onAdd"
          >新增</el-button
        >
        <!-- <el-button size="small" class="el_button" @click="importClick" icon="el-icon-download">导入</el-button> -->
        <el-dropdown @command="onDropdown">
          <el-button size="small" style="margin-left: 15px">
            批量操作<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <!-- <el-dropdown-item command="batch">批量操作</el-dropdown-item> -->
            <el-dropdown-item command="set">一键布防</el-dropdown-item>
            <el-dropdown-item command="remove">一键撤防</el-dropdown-item>
            <el-dropdown-item command="onimport">批量编辑</el-dropdown-item>
            <!-- <el-dropdown-item command="alarmReceiver">设置接警人管理</el-dropdown-item>
            <el-dropdown-item command="del">批量删除</el-dropdown-item> -->
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div class="content">
      <el-table
        :data="tableData"
        height="calc(100% - 65px)"
        class="table"
        @selection-change="batchSelect"
        :header-cell-style="headerStyle"
        row-key="id"
        ref="refMultipleTable"
      >
        <el-table-column
          align="center"
          type="selection"
          :reserve-selection="true"
          min-width="40"
        >
        </el-table-column>
        <el-table-column align="center" label="序号" type="index" width="80">
        </el-table-column>
        <el-table-column
          align="center"
          prop="name"
          label="建筑物名称"
          min-width="120"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="address"
          label="地址"
          min-width="120"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="floorCount"
          label="楼层数"
          min-width="120"
        >
          <template slot-scope="{ row }">
            <span @click="searchSpaceClick(row)" class="search_space">{{
              row.floorCount
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="spaceCount"
          label="安装点"
          min-width="120"
        >
        </el-table-column>

        <!-- <el-table-column align="center" prop="isDefence" label="布防状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isDefence == 0" type="warning">已撤防</el-tag>
            <el-tag v-else type="success">已布防</el-tag>
          </template>
        </el-table-column> -->

        <el-table-column
          align="center"
          prop="orgName"
          label="组织机构"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>

        <el-table-column
          align="center"
          prop="village"
          label="小区"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>

        <el-table-column
          align="center"
          prop="management"
          label="操作"
          width="200"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="布防"
              placement="bottom"
            >
              <i
                @click="onSet(scope.row)"
                class="iconfont anquan1 tableBtnIcon"
              ></i>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="撤防"
              placement="bottom"
            >
              <i
                @click="onRemove(scope.row)"
                class="iconfont iconfontquxiaoshouquan tableBtnIcon"
              ></i>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑"
              placement="bottom"
            >
              <i
                @click="onEdit(scope.row)"
                class="iconfont tianxie tableBtnIcon"
              ></i>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="bottom"
            >
              <i
                @click="onDel(scope.row.id)"
                class="iconfont shanchu tableBtnIcon"
              ></i>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="total"
        :page.sync="page"
        :limit.sync="limit"
        @pagination="SpaceManager"
        class="pagination"
      />
    </div>
    <addModel
      ref="refAdd"
      :getLocationInfo="getLocationInfo"
      :getAddressflag="getAddressflag"
    ></addModel>
    <editModel
      ref="refEdit"
      :getLocationInfo="getLocationInfo"
      :editInfo="editInfo"
      :getAddressflag="getAddressflag"
    >
    </editModel>
    <batchModel ref="refBatch"></batchModel>
    <alarmReceiver ref="refAlarmReceiver"></alarmReceiver>
    <ImportBuildings ref="refImportBuildings"></ImportBuildings>
  </div>
</template>

<script>
import addModel from "./components/addModel.vue";
import editModel from "./components/editModel.vue";
import batchModel from "./components/batchModel.vue";
import alarmReceiver from "./components/alarmReceiver.vue";
import ImportBuildings from "./components/ImportBuildings.vue";
import Tree from "./components/tree";
import tableStyleMixin from "@mixin/table-style";
import Pagination from "@components/Pagination.vue";
import { handleTree } from "@utils/trans-tree";
import {
  reqSpaceManager,
  // reqParkList,
  reqDel,
  reqUpdate,
  reqOrgList,
  reqBatchDefence,
} from "@/api/api";
import { mapState } from "vuex";
import treeselect from "@riophae/vue-treeselect"; //树形选择器
// import "@components/vue-treeselect.less"; //树形选择器
import "@components/vue-treeselect.less";
import { LOAD_CHILDREN_OPTIONS } from "@riophae/vue-treeselect"; //Vue-Treeselect三级动态加载
import loadMore from "@mixin/loadMore";
import { jsonp } from "vue-jsonp"; //使用jsonp

export default {
  name: "buildingsManage-list",
  components: {
    Tree,
    Pagination,
    addModel,
    editModel,
    batchModel,
    alarmReceiver,
    ImportBuildings,
    treeselect,
  },
  mixins: [tableStyleMixin, loadMore],
  data() {
    return {
      normalizer(node) {
        return {
          id: node.id,
          label: node.orgName,
          children: node.children,
        };
      },
      getAddressflag: false, //地图选点
      loading: false,
      loadingSearch: false, //查询按钮loading
      search_val: "",
      orgId: null,
      page: 1,
      limit: 10,
      total: 0,
      tableData: [],
      getLocationInfo: {
        getLat: "",
        getLng: "",
        getAdd: "",
        province: "",
        city: "",
        area: "",
        provinceCityAreaValue: "",
      },
      editInfo: {},
      batchDate: [],
      // ParkList: [],
      projectList: [], //单位数据
      sysInstanceIndex: 1,
      sysInstanceTotalPages: 10,
      flag: true,
      selectedValue: "",
      orgName: "",
    };
  },
  mounted() {
    this.addListenAddress();
  },
  computed: {
    ...mapState(["user"]),
  },
  methods: {
    // 清空
    handleClear() {
      this.selectedValue = "";
      this.orgName = "";
      this.sysInstanceIndex = 1;
      this.sysInstanceTotalPages = 10;
      this.projectList = [];
      this.OrgList();
    },
    // 远程搜索
    async remoteMethod(query) {
      this.selectedValue = query; //保留输入的值
      this.orgName = query; //保留输入的值
      this.sysInstanceIndex = 1;
      this.sysInstanceTotalPages = 10;
      this.projectList = [];
      this.OrgList();
    },
    async loadMore() {
      if (this.sysInstanceIndex >= Math.ceil(this.sysInstanceTotalPages / 10))
        return;
      this.sysInstanceIndex++;
      this.loading = true;
      // 获取列表数据的方法
      await this.OrgList();
      this.loading = false;
    },
    // 获取单位列表
    async OrgList() {
      var res = await reqOrgList( {
        userId: this.user.userId,
        roleName: this.user.roleName,
        tenantId: this.user.tenantId,
        orgName: this.orgName,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      // console.log(res);
      // this.sysInstanceTotalPages = res.data.total;
      // this.projectList = [...this.projectList, ...res.data.rows];
      this.projectList =res.data.rows
    },
    // 选择单位
    changeOrgId(e) {
      this.orgId = e;
      this.page = 1;
      this.limit = 10;
      this.SpaceManager();
    },
    // 下拉请求列表
    enterpriseChange(val) {
      if (val && this.flag) {
        this.OrgList();
        this.flag = false; //只执行一次
      }
    },
    // 查看楼层管理
    searchSpaceClick(row) {
      // console.log(row);
      this.$router.push({
        name: "floorsManage",
        params: { id: row.id, name: row.name },
      });
    },
    // 清空
    clearNickname() {
      this.page = 1;
      this.limit = 10;
      this.SpaceManager();
    },
    //查询
    async searchClick() {
      this.page = 1;
      this.limit = 10;
      this.loadingSearch = true;
      await this.SpaceManager();
      this.loadingSearch = false;
    },
    // 园区列表
    // async getreqParkList() {
    //   let res = await reqParkList(1, 100, {
    //     userId: this.user.userId,
    //     roleName: this.user.roleName,
    //   });
    //   if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
    //   this.ParkList = res.data.rows;
    // },

    // 监听获取经纬度
    addListenAddress() {
      window.addEventListener(
        "message",
        (event) => {
          // console.log(event);
          // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
          let loc = event.data;
          // console.log(loc);
          // console.log(loc.module);
          if (loc && loc.module == "locationPicker") {
            //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
            // console.log(loc, "loc");
            this.getAddress(loc.latlng.lat, loc.latlng.lng, loc.poiname);
            // this.isShowMap = false
          }
        },
        false
      );
    },
    // 获取地址信息
    getAddress(lat, lng, poiname) {
      jsonp(
        `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53`,
        {
          output: "jsonp",
        }
      )
        .then((res) => {
          // console.log(res);
          this.getAddressflag = !this.getAddressflag;
          let { province, city, district } = res.result.ad_info;
          let { title } = res.result.address_reference.town;
          // console.log(res.result, "res.result.ad_info");
          this.$set(this.getLocationInfo, "getLat", lat);
          this.$set(this.getLocationInfo, "getLng", lng);
          this.$set(this.getLocationInfo, "province", province);
          this.$set(this.getLocationInfo, "city", city);
          this.$set(this.getLocationInfo, "district", district);
          this.$set(this.getLocationInfo, "street", title);
          // 详细位置
          this.$set(
            this.getLocationInfo,
            "getAdd",
            this.stripscript(poiname).length > 20
              ? this.stripscript(poiname).substr(0, 20)
              : this.stripscript(poiname)
          );
        })
        .catch((err) => {
          // console.log(err, "err");
        });
    },
    // 过滤特殊字符
    stripscript(s) {
      let pattern = new RegExp(
        "[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）&mdash;—|{}【】‘；：”“'。，、？]"
      );
      let rs = "";
      for (let i = 0; i < s.length; i++) {
        rs = rs + s.substr(i, 1).replace(pattern, "");
      }
      return rs;
    },
    // 选择复选框批量添加联系人
    batchSelect(arr) {
      this.batchDate = [];
      // this.exportList = [];
      // this.exportList = arr;
      arr.forEach((c) => {
        this.batchDate.push(c.id);
      });
      // console.log(this.batchDate, "this.batchDate");
    },
    // 更多操作回调事件
    onDropdown(e) {
      switch (e) {
        case "batch":
          this.$refs.refBatch.dialogVisible = true;
          break;
        case "set":
          if (this.batchDate.length <= 0) {
            this.$modal.notifyWarning("请勾选要操作的建筑物");
            return;
          }
          this.$confirm(
            "一键布防将对该建筑物下所有楼层及安装点同时进行布防，确认后将更新该建筑物下所有楼层及安装点为布防状态。",
            "建筑物批量布防",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(async () => {
              const res = await reqBatchDefence({
                spaceIdList: this.batchDate,
                isDefence: 1,
              });
              if (res.code !== 20000)
                return this.$modal.notifyWarning(res.message);
              this.$modal.notifySuccess("批量设置布防成功!");
              this.SpaceManager();
              this.clearSelections(); //清空复选框
            })
            .catch(() => {});
          break;
        case "remove":
          if (this.batchDate.length <= 0) {
            this.$modal.notifyWarning("请勾选要操作的建筑物");
            return;
          }
          this.$confirm(
            "一键撤防将对该建筑物下所有楼层及安装点同时进行撤防，确认后将更新该建筑物下所有楼层及安装点为撤防状态。",
            "建筑物批量撤防",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(async () => {
              const res = await reqBatchDefence({
                spaceIdList: this.batchDate,
                isDefence: 0,
              });
              if (res.code !== 20000)
                return this.$modal.notifyWarning(res.message);
              this.$modal.notifySuccess("批量设置撤防成功!");
              this.SpaceManager();
              this.clearSelections(); //清空复选框
            })
            .catch(() => {});
          break;
        case "onimport":
          this.$refs.refImportBuildings.OrgList();
          this.$refs.refImportBuildings.dialogVisible = true;
          break;
        case "del":
        case "alarmReceiver":
          this.$refs.refAlarmReceiver.dialogVisible = true;
          break;
        case "del":
        // console.log("del");
      }
    },
    // 清空复选框√√
    clearSelections() {
      this.$refs.refMultipleTable.clearSelection();
    },
    // 新增
    onAdd() {
      // this.$refs.refAdd.OrgList();
      // this.$refs.refAdd.getreqParkList();
      this.$refs.refAdd.dialogVisible = true;
      this.$refs.refAdd.closeEditDialog2(); //防止出现表单验证
      this.$refs.refAdd.RegionList();
    },
    onSet(row) {
      // 布防
      this.$confirm("确定布防该建筑物吗？", "布防", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          row.isDefence = 1;
          const res = await reqUpdate(row);
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("布防成功!");
          this.SpaceManager();
        })
        .catch(() => {});
    },
    onRemove(row) {
      // 撤防
      this.$confirm("确定撤防该建筑物吗？", "撤防", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          row.isDefence = 0;
          const res = await reqUpdate(row);
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("撤防成功!");
          this.SpaceManager();
        })
        .catch(() => {});
    },
    onEdit(item) {
      //   console.log(item, "item");
      // this.getLocationInfo = item;
      this.editInfo = JSON.parse(JSON.stringify(item));
      this.$refs.refEdit.dialogVisible = true;
      this.$refs.refEdit.RegionList();
      this.$refs.refEdit.cityArr();
      this.$refs.refEdit.areaArr();
      this.$refs.refEdit.RegionLevelList();
      this.$refs.refEdit.communitylList();
    },
    onDel(id) {
      this.$confirm("此操作将永久删除该建筑物, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await reqDel({
            id,
            userId: this.user.userId,
          });
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("删除建筑物成功");
          this.SpaceManager();
        })
        .catch(() => {});
    },
    // 建筑物列表
    async SpaceManager() {
      let res = await reqSpaceManager(this.page, this.limit, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        name: this.search_val,
        orgId: this.orgId,
        metaCode: 1,
        isStatistics: 1,
      });
      //   console.log(res.data);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.tableData = res.data.rows;
      this.total = res.data.total;
    },
  },
  created() {
    this.SpaceManager();
    // this.getreqParkList();
  },
};
</script>

<style scoped lang="less">
@import url("~@views/style/tablePage.less");

.header_left {
  display: flex;
}

// 查看关联安装点
.search_space {
  padding: 0 10px;
  cursor: pointer;

  &:hover {
    color: #7367f0;
  }
}

::v-deep .el-button--small {
  background: #7367f0;
  color: #fff;
  border: none;
}

// 下拉框加载开始
.div_box {
  height: 276px;
  position: absolute;
  top: -1px;
  left: -1px;
  width: 100%;
  z-index: 9999;
  // background: red;
  // opacity: 0.5;
}

::v-deep .el-loading-mask {
  border-radius: 4px;
}

// 下拉框加载结束
</style>
